import type { App } from 'vue'
import type { RouteRecordRaw } from 'vue-router'
import { createRouter, createWebHistory } from 'vue-router'
import { qiankunWindow } from 'vite-plugin-qiankun/dist/helper'
import { isRelogin } from '@/configs/axios/service'
import { useNProgress } from '@/hooks/basic/useNProgress'
import { useTitle } from '@/hooks/basic/useTitle'
import { useAppStoreWithOut } from '@/store/modules/app'
import { useUserStoreWithOut } from '@/store/modules/user'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { getAccessToken } from '@/utils/business/auth'
import { remainingRouter } from './routes'

const { start, done } = useNProgress()
const appStore = useAppStoreWithOut()
const docTitle = useTitle()

const router = createRouter({
  history: createWebHistory(
    qiankunWindow.__POWERED_BY_QIANKUN__ 
      ? 
      `/cjui-admin-vue3${import.meta.env.VITE_APP_BASE_URL}`
      : 
      `${import.meta.env.VITE_APP_BASE_URL}`
  ),
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 }),
  routes: remainingRouter as RouteRecordRaw[],
})

// 路由不重定向白名单
const whiteList = [
  '/login',
  '/register'
]

// 路由加载前
router.beforeEach(async (to, from, next) => {
  start()
  if (getAccessToken()) {
    if (to.path === '/login') {
      next({ path: '/' })

    } else {
      const userStore = useUserStoreWithOut()
      const permissionStore = usePermissionStoreWithOut()

      if (!userStore.getIsSetUser) {
        isRelogin.show = true
        await userStore.setUserInfoAction()
        isRelogin.show = false

        // 后端过滤菜单
        await permissionStore.generateRoutes()
        permissionStore.getAddRouters.forEach((route) => {
          router.addRoute(route as unknown as RouteRecordRaw) // 动态添加可访问路由表
        })

        const redirectPath = from.query.redirect || to.path
        const redirect = decodeURIComponent(redirectPath as string)
        const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
        next(nextData)
        
      } else {
        next()
      }
    }

  } else {
    // @临时处理
    next()
    // if (whiteList.indexOf(to.path) !== -1) {
    //   next()
    // } else {
    //   next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
    // }
  }
})

router.afterEach((to) => {
  if (to?.meta?.title) {
    const { t } = useI18n()
    docTitle.value = to?.meta?.title ? `${appStore.title}|${t(to?.meta?.title)}` : appStore.title
  }
  done()
})

export const resetRouter = (): void => {
  const resetWhiteNameList = ['Redirect', 'Login', 'NoFind', 'Root']
  router.getRoutes().forEach((route) => {
    const { name } = route
    if (name && !resetWhiteNameList.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name)
    }
  })
}

export const setupRouter = (app: App<Element>) => {
  app.use(router)
}

export default router
